//
//  LGOpenDoorCell.m
//  celltest
//
//  Created by guomianxiang on 2017/4/7.
//  Copyright © 2017年 guomianxiang. All rights reserved.
//

#import "LGOpenDoorCell.h"
#import <SVProgressHUD.h>
#import "LGDCTableHead.h"

@interface LGOpenDoorCell ()

@property (strong, nonatomic) NSTimer *timer;

@end

@implementation LGOpenDoorCell


- (IBAction)openDoorBtnClick:(UIButton *)sender {
    
    [self changeOpenBtnSelect:YES];
    
    __weak typeof(self)weakSelf = self;
    
    [DCMI openDoor:self.content.door reply:^(BOOL success, NSError * _Nullable error) {
        
        [weakSelf.activityIndicator stopAnimating];
        weakSelf.activityIndicator.hidden = YES;
        
        if (success) {
            [SVProgressHUD showSuccessWithStatus:@"开门成功"];
            //关闭提示框
            [weakSelf closeHint];
            
            weakSelf.contentLab.text = @"打开";
        }else {
            [SVProgressHUD showErrorWithStatus:@"开门失败,请检查网络连接"];
            [weakSelf closeHint];
            weakSelf.contentLab.text = @"门不在线";
        }
        
        [weakSelf changeOpenBtnSelect:NO];
        
    }];
    
}

- (void)closeHint{
    dispatch_async(dispatch_get_main_queue(), ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SVProgressHUD dismiss];
            
        });
    });
}

- (void)changeOpenBtnSelect:(BOOL)select {
    self.openDoorBtn.selected = select;
    if (select) {
        self.openDoorBtnTitleLab.textColor = kColorFromRGB(0x3fedeb);
    }else {
        self.openDoorBtnTitleLab.textColor = [UIColor whiteColor];
    }
}


- (void)getDoorState{
    
    __weak typeof(self)weakSelf = self;
    
    if (!self.superview) {
        [self.timer invalidate];
        return;
    }
    
    [DCMI getDoorState:self.content.door reply:^(BOOL open, NSError * _Nullable error) {
        
        [weakSelf.activityIndicator stopAnimating];
        weakSelf.activityIndicator.hidden = YES;
        
        NSString *text;
        
        if (open) {
            text = @"打开";
        }else {
            if (error) {
                text = @"门不在线";
            }else {
                text = @"关闭";
            }
        }
        
        self.contentLab.text = text;
    }];
    
}

- (void)setContent:(LGDCCellContent *)content {
    [super setContent:content];
    
    self.activityIndicator.hidden = NO;
    [self.activityIndicator startAnimating];
    self.contentLab.text = @"     正在查询...";
    
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(getDoorState) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}


- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

@end
